#include "samples.h"

SHELL_CMD_FN(_os_sample_work);

SHELL_REGISTER_CMD(
    register_sample_work,
    SHELL_SETUP_CMD("sample-work", "OS API example of: work", _os_sample_work, NULL), //
);

static os_work_q_t s_work_q_handle;
static os_work_t s_work1_handle;
static os_work_t s_work2_handle;
static os_work_t s_work3_handle;

static void _work_1(void *arg)
{
    sh_t *sh_hdl = arg;
    os_time_t time = os_get_sys_time();
    printf("%s: running. sys run time: %d.%03d second\r\n", __FUNCTION__, time / 1000, time % 1000);

    printf("wakeup the works to test\r\n");
    os_work_resume(&s_work2_handle, 0);
    os_work_resume(&s_work3_handle, 0);

    printf("use 'yield' to execute works in the work-queue that are greater or equal to the current level\r\n");
    os_work_yield(100);

    printf("use 'sleep' to execute most of the works in the work-queue\r\n");
    os_work_sleep(100);

    printf("use 'later' to execute this work again ...\r\n\r\n");
    os_work_later(1000);
}

static void _work_2(void *arg)
{
    sh_t *sh_hdl = arg;
    os_time_t time = os_get_sys_time();
    printf("%s: running. sys run time: %d.%03d second\r\n", __FUNCTION__, time / 1000, time % 1000);
}

static void _work_3(void *arg)
{
    sh_t *sh_hdl = arg;
    os_time_t time = os_get_sys_time();
    printf("%s: running. sys run time: %d.%03d second\r\n", __FUNCTION__, time / 1000, time % 1000);
}

SHELL_CMD_FN(_os_sample_work)
{
    tag();

    do
    {
        printf("create work-queue\r\n");
        os_work_q_create(&s_work_q_handle, "test-work-q", 0x400, OS_PRIORITY_LOW);

        printf("create work 1, priority = 1\r\n");
        os_work_create(&s_work1_handle, "work1", _work_1, sh_hdl, 1);

        printf("create work 2, priority = 0\r\n");
        os_work_create(&s_work2_handle, "work2", _work_2, sh_hdl, 0);

        printf("create work 3, priority = 2\r\n");
        os_work_create(&s_work3_handle, "work3", _work_3, sh_hdl, 2);

        printf("must submit the work object to work-queue object\r\n");
        os_work_submit(&s_work_q_handle, &s_work2_handle, OS_WAIT_FOREVER);
        os_work_submit(&s_work_q_handle, &s_work3_handle, OS_WAIT_FOREVER);
        os_work_submit(&s_work_q_handle, &s_work1_handle, OS_WAIT_FOREVER);

        printf("start test work\r\n\r\n");
        os_work_submit(&s_work_q_handle, &s_work1_handle, 0);

        os_thread_sleep(3000);

        printf("sample complete. delete works and work-queue\r\n");
        os_work_delete(&s_work1_handle);
        os_work_delete(&s_work2_handle);
        os_work_delete(&s_work3_handle);
        os_work_q_delete(&s_work_q_handle);

        return 0;

    } while (0);
}
